<template>
  <div class="page-container">
    <el-container>
      <el-aside class="page-aside" width="280px" v-drag v-collapse>
        <div class="title">
          <div class="title-content">目录</div>
          <div class="title-button">
            <div class="button-list">
              <div class="button-item">
                <ac-icon
                  iconId="018dca412c4e207388f7"
                  :style="'cursor: pointer;color: ' + (treeCheck ? 'rgb(0,133,246)' : '#999') + ';font-size: 18px;'"
                  :title="treeCheck ? '导入模式' : '导出模式'"
                  @click.stop="changeMode"
                />
              </div>
              <div class="button-item">
                <ac-icon
                  iconId="018ece4f749ec5911772"
                  style="cursor: pointer;color: rgb(0,133,246); font-size: 18px;"
                  title="导出页面"
                  @click.stop="handleExport"
                />
              </div>
              <div class="button-item">
                <el-upload
                  action=""
                  :http-request="handleImport"
                  :show-file-list="false"
                  accept=".dat"
                >
                  <ac-icon
                    iconId="018ece4f70fcf0627f81"
                    style="cursor: pointer;color: rgb(0,133,246); font-size: 18px;"
                    title="导入页面"
                  />
                </el-upload>
              </div>
            </div>
            <el-dropdown trigger="hover">
              <span class="title-button-box">
                <ac-icon iconId="018dc9c3efed46e8b927" size="18" @click.stop />
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click.stop="addPage({})">
                    <ac-icon iconId="018dc9c3efb74ac607cb" color="#67C23A" style="margin-right: 5px" /> 新增页面
                  </el-dropdown-item>
                  <el-dropdown-item @click.stop="addFolder({})" :divided="true">
                    <ac-icon iconId="018dc9c3efed6d208a59" color="orange" style="margin-right: 5px" /> 新增目录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div class="filter-box">
          <el-input placeholder="搜索" v-model="filterText" clearable />
        </div>
        <div class="page-aside-grow">
          <el-tree
            ref="tree"
            class="tree"
            node-key="id"
            v-loading="treeLoading"
            element-loading-text="数据加载中..."
            :data="treeData"
            :props="treeProps"
            :highlight-current="true"
            :default-expanded-keys="treeExpand"
            :filter-node-method="filterNode"
            :expand-on-click-node="true"
            @node-click="nodeClick"
            :show-checkbox="treeCheck"
          >
            <template v-slot="{ node, data }">
              <div class="node-item">
                <span v-if="data.type === 'folder'" class="icon">
                  <ac-icon v-if="node.expanded" color="orange" iconId="018dc9c3efedbb59d0b3" />
                  <ac-icon v-else color="orange" iconId="018dc9c3efed6d208a59" />
                </span>
                <span v-else-if="data.type === 'page'" class="icon">
                  <ac-icon color="#117fe8" iconId="018dc9c3efb74ac607cb" />
                </span>
                <span class="node-label" :title="data.text"><span>{{data.text}}</span></span>
                <div class="node-button" v-if="data.type==='folder'">
                  <el-dropdown trigger="hover" placement="bottom-start">
                    <span class="node-button-item">
                      <ac-icon iconId="018dca6283a1e534a046" @click.stop />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="addPage(data.data)">
                          <ac-icon iconId="018dc9c3efb74ac607cb" color="#67C23A" style="margin-right: 5px" />新增页面
                        </el-dropdown-item>
                        <el-dropdown-item @click="addFolder(data.data)">
                          <ac-icon iconId="018dc9c3efed6d208a59" color="orange" style="margin-right: 5px" />新增目录
                        </el-dropdown-item>
                        <el-dropdown-item @click="updateNode(data.data)">
                          <ac-icon iconId="018dca6db20c6a3aaf68" color="#0085f6" style="margin-right: 5px" />修改目录
                        </el-dropdown-item>
                        <el-dropdown-item @click="moveNode('folder', data.data)">
                          <ac-icon iconId="018dca444e0754edef13" color="#FF6600" style="margin-right: 5px" />移动目录
                        </el-dropdown-item>
                        <el-dropdown-item @click="deleteNode(data.data)">
                          <ac-icon iconId="018dc9c3efd3a0502886" color="#F56C6C" style="margin-right: 5px" />删除目录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="node-button" v-if="data.type==='page'">
                  <el-dropdown trigger="hover" placement="bottom-start">
                    <span class="node-button-item">
                      <ac-icon iconId="018dca6283a1e534a046" @click.stop />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="moveNode('page', data.data)">
                          <ac-icon iconId="018dca444e0754edef13" color="#FF6600" style="margin-right: 5px" />移动页面
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </el-aside>
      <el-main class="page-main">
        <ac-table
          ref="dataTable"
          pkName="id"
          :filters="filters"
          :filterFields="filterFields"
          :columns="columns"
          @handleTableOperator="handleTableOperator"
          @handleAjaxSuccess="handleAjaxSuccess"
        ></ac-table>
      </el-main>
    </el-container>
  </div>

  <!--新增/编辑目录界面-->
  <el-dialog
    v-model="folderVisible"
    :title="folderTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="folderForm"
      label-width="120px"
      label-position="right"
      :model="folderData"
      :rules="folderRules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="目录名称" prop="name">
            <el-input v-model="folderData.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级目录" prop="parentId">
            <ac-tree
              v-model="folderData.parentId"
              dataUrl="/system/pageFolder/queryTree"
              :leafSelect="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="folderVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="folderLoading"
        @click="submitFolderForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--移动目录界面-->
  <el-dialog
    v-model="moveVisible"
    :title="moveTitle"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
    draggable
  >
    <el-form
      ref="moveForm"
      label-width="120px"
      label-position="right"
      :model="moveData"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item :label="moveData.opType === 'folder' ? '目录' : '页面'">
            <ac-input
              v-model="moveData.name"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="移动到" prop="folderId">
            <ac-tree
              v-model="moveData.folderId"
              dataUrl="/system/pageFolder/queryTree"
              :leafSelect="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="moveVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="moveLoading"
        @click="submitMoveForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--页面编辑-->
  <el-dialog
    v-model="pageVisible"
    class="no-padding"
    :title="pageTitle"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
    draggable
  >
    <PageEdit ref="page" :options="pageData" @afterSubmit="afterPageSubmit"/>
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="pageVisible=false"
      >取消</el-button>
      <el-button
        type="primary"
        size="default"
        :loading="pageLoading"
        @click="submitPageForm"
      >提交</el-button>
    </template>
  </el-dialog>

  <!--页面预览-->
  <el-dialog
    v-model="previewVisible"
    :title="previewTitle"
    :close-on-click-modal="false"
    class="no-padding"
    destroy-on-close
    fullscreen
    draggable
  >
    <div style="height: 100%;display: flex;flex-direction: column">
      <codeless-page
        v-if="previewPageInfo.type === '普通' || previewPageInfo.type === '标签'"
        :pageInfo="previewPageInfo"
      />
      <visual-page
        v-else-if="previewPageInfo.type === '可视化' && previewPageInfo.layoutMode !== '大屏'"
        :pageInfo="previewPageInfo"
      />
      <dashboard-page
        v-else-if="previewPageInfo.type === '可视化'"
        :pageInfo="previewPageInfo"
      />
    </div>
  </el-dialog>

  <el-dialog
    v-model="relationVisible"
    class="no-padding"
    title="关系图谱"
    :close-on-click-modal="false"
    destroy-on-close
    fullscreen
  >
    <relation-page :pageId="relationPageId" />
    <template #footer>
      <el-button
        size="default"
        type="info"
        @click="relationVisible=false"
      >关闭</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
@import "@/assets/style/codeless.css";
@import "@/assets/style/visual.css";
</style>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/http/api';
import PageEdit from "@/admin/codeless/pageEdit.vue";
import tool from "@/utils/tool";
import CodelessPage from "@/codeless/view/page.vue";
import VisualPage from "@/visual/view/page.vue";
import DashboardPage from "@/dashboard/view/page.vue";
import RelationPage from "@/admin/codeless/relationPage.vue";
import { clearCache } from "@/utils/codeless";

const tree = ref();
const filterText = ref('');
const treeLoading = ref(false);
const treeKey = ref('');
const treeData = ref([]);
const treeExpand = ref([]);
const treeCheck = ref(false);
const treeProps = ref({
  children: 'children',
  label: function(data) {
    return data.text +
      (data.data.code !== undefined && data.data.code != null
        ? ' [' + data.data.code + ']　' : '　')
  }
});

const folderTitle = ref('');
const folderVisible = ref(false);
const folderLoading = ref(false);
const folderForm = ref();
const folderData = ref({});
const folderRules = ref({
  name: [{required: true, message: '请输入目录名称', trigger: ['blur', 'change']}],
});

const moveTitle = ref('');
const moveVisible = ref(false);
const moveLoading = ref(false);
const moveForm = ref();
const moveData = ref({});

const dataTable = ref();
const filters = ref({
  folderId: '',
  name: '',
});
const filterFields = ref([
  {prop: "name", label: "名称"},
  {prop: "type", label: "展示类型", type: 'select', options: '普通,标签,可视化'},
]);
const columns = ref([
  {prop: "name", label: "名称", minWidth: 160},
  {prop: "type", label: "展示类型", width: 100, align: 'center', type: 'radio', options: '普通,标签,可视化'},
  {prop: "updateTime", label: "更新时间", width: 160, align: 'center', type: "datetime"}
]);

const pageVisible = ref(false);
const pageTitle = ref('');
const pageData = ref({});
const pageLoading = ref();
const page = ref();

const previewVisible = ref(false);
const previewTitle = ref('');
const previewPageInfo = ref({});

const relationVisible = ref(false);
const relationPageId = ref('');

const changeMode = () => {
  treeCheck.value = !treeCheck.value;
  if (treeCheck.value) {
    tree.value.setCheckedNodes([]);
  }
}

const handleExport = () => {
  const nodes = tree.value.getCheckedNodes(false, true);
  if (!nodes || nodes.length === 0) {
    ElMessage.error("请先选择页面！");
    return;
  }
  const data = {folderIds: [], pageIds: []};
  nodes.forEach(node => {
    if (node.type === 'folder') {
      data.folderIds.push(node.id);
    } else if (node.type === 'page') {
      data.pageIds.push(node.id);
    }
  });
  api.downloadFile('/system/page/exportData', data).then(res => api.saveFileLocal(res));
};

const handleImport = (file) => {
  api.uploadFile('/system/page/importData', {'file': file.file}).then((res) => {
    ElMessage.success(res.message);
    loadTreeData();
    dataTable.value.findPage();
  });
};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.text.indexOf(value) >= 0
    || (data.data.code != null && data.data.code.indexOf(value) >= 0);
};

const currNode = ref(null);
const nodeClick = (data, treeNode) => {
  if (currNode.value && currNode.value.id === data.id) {
    treeNode.checked = !treeNode.checked;
  } else {
    treeNode.checked = true;
  }

  if (treeNode.checked) {
    currNode.value = data;
    if (data.type === 'folder') {
      filters.value.folderId = data.id || '';
      filters.value.id = '';
    } else {
      filters.value.folderId = '';
      filters.value.id = data.id || '';
    }
    dataTable.value.refreshPage(1);
  } else {
    tree.value.setCurrentKey(null);
    currNode.value = null;
    filters.value.folderId = '';
    dataTable.value.refreshPage(1);
  }
};

const addPage = (data) => {
  pageData.value = {folderId: data.id};
  pageTitle.value = "新增页面";
  pageVisible.value = true;
};

const addFolder = (data) => {
  showFolderDialog('新增', {parentId: data.id || '', ordinal: 10});
};

const showFolderDialog = (tips, data) => {
  folderTitle.value = tips + '目录';
  folderVisible.value = true;
  folderData.value = Object.assign({}, data);
  folderForm.value && folderForm.value.resetFields();
};

const updateNode = (data) => {
  showFolderDialog('修改', data);
};

const moveNode = (opType, data) => {
  moveTitle.value = opType === 'folder' ? '移动目录' : '移动页面';
  moveVisible.value = true;
  moveData.value = {
    opType: opType,
    id: data.id,
    name: data.name,
    labelName: opType === 'folder' ? '目录' : '移动页面',
    folderId: opType === 'folder' ? data.parentId : data.folderId
  };
  moveForm.value && moveForm.value.resetFields();
};

const deleteNode = (data) => {
  const url = '/system/pageFolder/delete';
  ElMessageBox.confirm('请确认是否删除【' + data.name + '】？', '提示', {type: 'warning'}).then(() => {
    api.post(url, {id: data.id}).then(res => {
      ElMessage.success(res.message);
      treeExpand.value.push(data.parentId || '0');
      treeExpand.value.push(data.folderId || '0');
      treeKey.value = data.parentId || data.folderId || '0';
      loadTreeData();
    });
  }).catch(() => {});
};

const submitFolderForm = () => {
  folderForm.value && folderForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        folderLoading.value = true;

        api.post('/system/pageFolder/save', folderData.value).then(res => {
          ElMessage.success(res.message);
          folderVisible.value = false;
          folderLoading.value = false;
          treeExpand.value.push(res.data.id || '0');
          treeKey.value = res.data.id || '0';
          loadTreeData();
        }).catch(() => {
          folderLoading.value = false;
        });
      }).catch(() => {});
    }
  });
};

const submitMoveForm = () => {
  moveForm.value && moveForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        moveLoading.value = true;
        const data = {id: moveData.value.id};
        let url;
        if (moveData.value.opType === 'folder') {
          data.parentId = moveData.value.folderId;
          url = '/system/pageFolder/updateParentId';
        } else {
          data.folderId = moveData.value.folderId;
          url = '/system/page/updateFolder'
        }
        api.post(url, data).then(res => {
          ElMessage.success(res.message);
          moveVisible.value = false;
          moveLoading.value = false;
          treeExpand.value.push(res.data.id || '0');
          treeKey.value = res.data.id || '0';
          loadTreeData();
        }).catch(() => {
          moveLoading.value = false;
        })
      }).catch(() => {});
    }
  });
};

const handleTableOperator = async(button, row) => {
  if (button.buttonType === 'add') {
    pageData.value = {folderId: filters.value.folderId};
    pageTitle.value = "新增页面";
    pageVisible.value = true;
  } else if (button.buttonType === 'edit') {
    pageData.value = tool.deepClone(row);
    pageTitle.value = "编辑页面";
    pageVisible.value = true;
  } else if (button.buttonType === 'preview') {
    clearCache();
    previewTitle.value = '【' + row.name + '】页面预览';
    const res = await api.post('/system/page/queryBy', {id: row.id});
    previewPageInfo.value = res.data || {};
    previewVisible.value = true;
  } else if (button.buttonType === 'relation') {
    relationPageId.value = row.id;
    relationVisible.value = true;
  }
};

const handleAjaxSuccess = () => {
  loadTreeData();
};

const submitPageForm = () => {
  page.value.submitData();
};

const afterPageSubmit = (data) => {
  pageVisible.value = false;
  dataTable.value.findPage();
  treeExpand.value = [data.folderId || '0'];
  loadTreeData();
};

const loadTreeData = () => {
  treeLoading.value = true;
  api.post('/system/page/queryTree').then(res => {
    const node = tree.value.getCurrentNode();
    if (node !== undefined && node != null) {
      treeExpand.value = [node.id, node.data.parentId, node.data.folderId, '0'];
    }
    treeData.value = res.data.children;
    treeLoading.value = false;
    if (treeKey.value) {
      nextTick(() => {
        tree.value.setCurrentKey(treeKey.value);
      });
    }
  }).catch(() => {
    treeLoading.value = false;
  });
};

watch(() => filterText.value, val => {
  tree.value.filter(val);
});

onMounted(() => {
  loadTreeData();
});
</script>

<style scoped lang="scss">
.title {
  display: flex;
  flex-direction: row;
  margin-right: 10px;
  height: 40px;
  align-items: center;

  .title-content {
    flex-grow: 1;
    font-size: 18px;
  }
  .title-button {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }
  .title-button .button-list {
    display: flex;
    flex-direction: row;
    align-items: center;
    .button-item {
      margin: 0 5px 0 5px;
    }
  }
  .title-button .title-button-box {
    height: 30px;
    width: 40px;
    border-radius: 5px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    border: none;
    cursor: pointer;
  }

  .title-button .title-button-box:hover {
    background: #eaeaea;
    border: none;
  }

  .title-button .title-button-box:focus-visible {
    outline: unset;
  }
}

.filter-box {
  margin-right: 10px;
}

.tree :deep(.el-tree-node__content) {
  height: 40px;
}

.page-aside-grow {
  width: 100% !important;

  :deep(.el-tree) {
    display: flex;
    flex-direction: column;
    width: 1px !important;
  }

  :deep(.el-tree-node) {
    display: flex;
    flex-direction: column;
    width: 100% !important;
  }

  :deep(.el-tree-node__content) {
    display: flex;
    flex-grow: 1;
  }
}

.node-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;

  .icon {
    display: flex;
    align-items: center;
  }

  .node-label {
    margin-left: 6px;
    flex-grow: 1;
    width: 1px;
    text-overflow: ellipsis;
    overflow: hidden;
    display: flex;

    > span {
      width: 100%;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .node-button {
    margin-right: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .node-button .node-button-item {
    height: 30px;
    width: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 5px;
  }
  .node-button .node-button-item:focus-visible {
    outline: unset;
  }
}
:deep(.el-tree-node:not(.is-current):focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content) {
  background-color: unset!important;
}
:deep(.el-tree-node:focus>.el-tree-node__content:hover) {
  background-color: #f5f7fa!important;
}
:deep(.el-tree-node.is-current:focus>.el-tree-node__content) {
  background-color: #ecf5ff!important;
}
.node-item:hover {
  .node-button .node-button-item:hover {
    background: #eaeaea;
  }
}
</style>